<?php

namespace app\common\model\problem;

use think\Model;

class BabycarProblem extends Model
{
    protected $name = 'babycar_problem';
    protected $pk = 'problem_id';

    // 问题类型常量
    const TYPE_COMMON = '常见问题';
    const TYPE_USAGE = '使用说明';
    const TYPE_OTHER = '其他问题';

    /**
     * 获取问题列表
     * @param array $params 查询参数
     * @return array
     */
    public function getList($params = [])
    {
        $where = [];
        
        // 只查询未删除的记录
        $where[] = ['is_deleted', '=', 0];
        
        // 按问题类型筛选
        if (!empty($params['type']) && in_array($params['type'], [
            self::TYPE_COMMON,
            self::TYPE_USAGE,
            self::TYPE_OTHER
        ])) {
            $where[] = ['type', '=', $params['type']];
        }
        
        // 按标题搜索
        if (!empty($params['title'])) {
            $where[] = ['title', 'like', '%' . $params['title'] . '%'];
        }

        // 构建查询
        $query = $this->where($where);
        
        // 添加排序
        $query->order('problem_id', 'desc');
        
        // 执行分页查询
        $list = $query->paginate([
            'list_rows' => 10,
            'query' => $params
        ]);

        return $list;
    }

    /**
     * 获取问题详情
     * @param int $problem_id
     * @return array|null
     */
    public function getDetail($problem_id)
    {
        return $this->where([
            'problem_id' => $problem_id,
            'is_deleted' => 0
        ])->find();
    }

    /**
     * 创建问题
     * @param array $data
     * @return bool
     */
    public function createProblem($data)
    {
        // 设置默认值
        if (!isset($data['is_show'])) {
            $data['is_show'] = '0';
        }
        if (!isset($data['is_deleted'])) {
            $data['is_deleted'] = '0';
        }
        return $this->save($data);
    }

    /**
     * 更新问题信息
     * @param int $problem_id
     * @param array $data
     * @return bool
     */
    public function updateProblem($problem_id, $data)
    {
        return $this->where([
            'problem_id' => $problem_id,
            'is_deleted' => 0
        ])->update($data);
    }

    /**
     * 软删除问题
     * @param int $problem_id
     * @return bool
     */
    public function deleteProblem($problem_id)
    {
        return $this->where([
            'problem_id' => $problem_id,
            'is_deleted' => 0
        ])->update(['is_deleted' => '1']);
    }

    /**
     * 获取所有问题类型
     * @return array
     */
    public static function getProblemTypes()
    {
        return [
            self::TYPE_COMMON,
            self::TYPE_USAGE,
            self::TYPE_OTHER
        ];
    }
} 